import * as cron from 'node-cron';
import { OilPriceService } from './oilPriceService';

export class SchedulerService {
  private static instance: SchedulerService;
  private oilPriceJob: cron.ScheduledTask | null = null;
  private isInitialized = false;

  private constructor() {}

  public static getInstance(): SchedulerService {
    if (!SchedulerService.instance) {
      SchedulerService.instance = new SchedulerService();
    }
    return SchedulerService.instance;
  }

  /**
   * 初始化定时任务
   */
  public initialize(): void {
    if (this.isInitialized) {
      console.log('定时任务服务已经初始化');
      return;
    }

    console.log('初始化定时任务服务...');

    // 每天凌晨2点更新油价数据
    this.oilPriceJob = cron.schedule(
      '0 2 * * *', // 每天凌晨2点执行
      async () => {
        try {
          const oilPriceService = OilPriceService.getInstance();
          await oilPriceService.updateOilPrices();
          console.log('定时油价数据更新任务完成');
        } catch (error) {
          console.error('定时油价数据更新任务失败:', error);
        }
      },
      {
        timezone: 'Asia/Shanghai',
      }
    );

    // 启动定时任务
    this.startOilPriceJob();

    this.isInitialized = true;
    console.log('定时任务服务初始化完成');
  }

  /**
   * 启动油价更新定时任务
   */
  public startOilPriceJob(): void {
    if (this.oilPriceJob) {
      this.oilPriceJob.start();
      console.log('油价更新定时任务已启动');
    }
  }

  /**
   * 停止油价更新定时任务
   */
  public stopOilPriceJob(): void {
    if (this.oilPriceJob) {
      this.oilPriceJob.stop();
      console.log('油价更新定时任务已停止');
    }
  }

  /**
   * 立即执行一次油价更新任务
   */
  public async executeOilPriceUpdate(): Promise<void> {
    console.log('手动执行油价数据更新任务...');
    try {
      const oilPriceService = OilPriceService.getInstance();
      await oilPriceService.updateOilPrices(true); // 强制更新
      console.log('手动油价数据更新任务完成');
    } catch (error) {
      console.error('手动油价数据更新任务失败:', error);
      throw error;
    }
  }

  /**
   * 获取定时任务状态
   */
  public getStatus(): {
    isInitialized: boolean;
    oilPriceJobRunning: boolean;
    nextOilPriceUpdate: Date | null;
  } {
    let nextOilPriceUpdate: Date | null = null;

    if (this.oilPriceJob) {
      // 计算下次执行时间（每天凌晨2点）
      const now = new Date();
      const next = new Date(now);
      next.setHours(2, 0, 0, 0);

      if (next <= now) {
        next.setDate(next.getDate() + 1);
      }

      nextOilPriceUpdate = next;
    }

    return {
      isInitialized: this.isInitialized,
      oilPriceJobRunning: !!this.oilPriceJob,
      nextOilPriceUpdate,
    };
  }

  /**
   * 销毁定时任务服务
   */
  public destroy(): void {
    if (this.oilPriceJob) {
      this.oilPriceJob.destroy();
      this.oilPriceJob = null;
    }

    this.isInitialized = false;
    console.log('定时任务服务已销毁');
  }
}
